package cn.mrcode.wxsdk.web.service;

import cn.mrcode.wxsdk.core.dialogue.common.exception.ReqException;
import cn.mrcode.wxsdk.core.dialogue.common.exception.WxException;
import cn.mrcode.wxsdk.core.dialogue.service.BaseService;
import cn.mrcode.wxsdk.web.protocol.res.WebAccessTokenResData;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 公用服务
 * @author zhuqiang
 * @version V1.0
 * @date 2015/9/18 11:42
 */
public class CommonService  extends BaseService {
    private static Logger log = LoggerFactory.getLogger(CommonService.class);
    private static final  String ACCESS_TOKEN_API = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    private static final String GRANT_TYPE = "authorization_code";
    /**
     * 通过 授权 code 获取针对 openid 调用接口的 授权 accessToken 中的 openid
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static String getOpenid(String appId, String appSecret, String code) throws ReqException, WxException {
        String url = ACCESS_TOKEN_API.concat("appid=").concat(appId)
                .concat("&secret=").concat(appSecret)
                .concat("&code=").concat(code)
                .concat("&grant_type=").concat(GRANT_TYPE);

            String resultJson = get(url);
            JSONObject resultObj = JSONObject.parseObject(resultJson);
            handerThrowErrcode(resultObj);
            WebAccessTokenResData wts = JSONObject.parseObject(resultJson, WebAccessTokenResData.class);
            return wts.getOpenid();
    }
}
